<template>
  <UserLayout :active-index="activeIndex" :active-menu="activeMenu">
    <div class="chat-content">
      <h1 class="page-title">消息聊天</h1>

      <!-- 聊天内容区 -->
      <div class="chat-area">
          <!-- 聊天头部 -->
          <div class="chat-header">
            <div class="header-left">
              <el-button @click="goBack" icon="ArrowLeft">返回</el-button>
              <div class="user-info">
                <el-avatar :size="40" :src="chatUser.avatar" />
                <div class="user-details">
                  <h3>{{ chatUser.name }}</h3>
                  <p :class="['status', { online: chatUser.online }]">
                    {{ chatUser.online ? '在线' : '离线' }}
                  </p>
                </div>
              </div>
            </div>
            <div class="header-right">
              <el-button icon="More" @click="showUserDetails">用户详情</el-button>
            </div>
          </div>

          <!-- 消息区域 -->
          <div class="chat-messages" ref="messagesContainer">
            <div class="messages-list">
              <div
                  v-for="message in messages"
                  :key="message.id"
                  :class="['message-item', message.sender === 'me' ? 'sent' : 'received']"
              >
                <div class="message-content">
                  <div class="message-text">{{ message.text }}</div>
                  <div class="message-time">{{ formatTime(message.time) }}</div>
                </div>
              </div>
            </div>
          </div>

          <!-- 输入区域 -->
          <div class="chat-input">
            <div class="input-tools">
              <el-button icon="Picture" circle size="small" @click="selectImage"></el-button>
              <el-button icon="Folder" circle size="small" @click="selectFile"></el-button>
            </div>
            <el-input
                v-model="newMessage"
                type="textarea"
                :rows="3"
                placeholder="输入消息..."
                @keydown.enter.exact.prevent="sendMessage"
                @keydown.enter.shift.exact.prevent="newMessage += '\n'"
            />
            <div class="input-actions">
              <el-button
                  type="primary"
                  @click="sendMessage"
                  :disabled="!newMessage.trim()"
                  :loading="sending"
              >
                发送
              </el-button>
            </div>
          </div>
        </div>
      </div>
  </UserLayout>
</template>

<script setup>
import { ref, onMounted, onBeforeUnmount, nextTick } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import UserLayout from '@/components/layout/UserLayout.vue'
import {
  ArrowLeft,
  More,
  Picture,
  Folder
} from '@element-plus/icons-vue'

const route = useRoute()
const router = useRouter()
const activeMenu = ref('messages')
const activeIndex = ref('4')
const newMessage = ref('')
const sending = ref(false)
const messagesContainer = ref(null)

// 聊天对象信息
const chatUser = ref({
  id: 101,
  name: '张三',
  avatar: 'https://cube.elemecdn.com/3/7c/3ea90e7f8a4d9f3d8f0e3b0e4e5b0jpeg.jpeg',
  online: true
})

// 消息列表
const messages = ref([
  {
    id: 1,
    sender: 'them',
    text: '您好，我对您发布的房源很感兴趣，想了解一下具体情况。',
    time: '15:25'
  },
  {
    id: 2,
    sender: 'me',
    text: '您好，很高兴您对我的房源感兴趣。请问您想了解哪些方面呢？',
    time: '15:26'
  },
  {
    id: 3,
    sender: 'them',
    text: '我想了解一下房子的具体位置和周边交通情况。',
    time: '15:27'
  },
  {
    id: 4,
    sender: 'me',
    text: '房子位于市中心，交通非常便利，地铁站步行5分钟，公交线路也很多。周边有大型商场和医院。',
    time: '15:28'
  },
  {
    id: 5,
    sender: 'them',
    text: '那太好了！我想预约明天下午看房，您方便吗？',
    time: '15:29'
  }
])

// WebSocket连接（模拟）
let websocket = null

// 格式化时间
const formatTime = (time) => {
  return time || new Date().toLocaleTimeString('zh-CN', { hour: '2-digit', minute: '2-digit' })
}

// 返回上一页
const goBack = () => {
  router.go(-1)
}

// 顶部导航栏跳转
const goToHome = () => {
  router.push('/')
}

const goToSearch = () => {
  router.push('/house/search')
}

const goToPublish = () => {
  router.push('/house/publish')
}

const goToMessages = () => {
  router.push('/message')
}

// 用户命令处理
const handleUserCommand = (command) => {
  switch (command) {
    case 'profile':
      router.push('/profile')
      break
    case 'settings':
      router.push('/settings')
      break
    case 'logout':
      ElMessage.success('退出登录成功')
      localStorage.removeItem('userEmail')
      localStorage.removeItem('isLoggedIn')
      router.push('/login')
      break
  }
}

// 侧边栏跳转
const goToPublishNew = () => {
  router.push('/house/publish')
}

const goToMyHouses = () => {
  router.push('/house/my-houses')
}

const goToAgentApply = () => {
  router.push('/agent/apply')
}

const goToAgentStatus = () => {
  router.push('/agent/status')
}

const goToAgentHouses = () => {
  router.push('/agent/houses')
}

const goToTenant = () => {
  router.push('/rental/tenant')
}

const goToLandlord = () => {
  router.push('/rental/landlord')
}

const goToAgentRental = () => {
  router.push('/rental/agent')
}

const goToProfile = () => {
  router.push('/profile')
}

// 菜单选择处理
const handleSelect = (key) => {
  switch (key) {
    case '1':
      router.push('/')
      break
    case '2':
      router.push('/house/search')
      break
    case '3':
      router.push('/house/publish')
      break
    case '4':
      router.push('/message')
      break
  }
}

// 显示用户详情
const showUserDetails = () => {
  ElMessage.info('查看用户详情')
}

// 选择图片
const selectImage = () => {
  ElMessage.info('选择图片功能')
}

// 选择文件
const selectFile = () => {
  ElMessage.info('选择文件功能')
}

// 发送消息
const sendMessage = () => {
  if (!newMessage.value.trim()) return

  sending.value = true

  // 模拟发送消息
  setTimeout(() => {
    const message = {
      id: messages.value.length + 1,
      sender: 'me',
      text: newMessage.value,
      time: new Date().toLocaleTimeString('zh-CN', { hour: '2-digit', minute: '2-digit' })
    }

    messages.value.push(message)
    newMessage.value = ''
    sending.value = false

    // 滚动到底部
    scrollToBottom()

    // 模拟对方回复
    simulateReply()
  }, 300)
}

// 模拟对方回复
const simulateReply = () => {
  setTimeout(() => {
    const replies = [
      '好的，我了解了。',
      '谢谢您的回复。',
      '明白了，我会考虑的。',
      '好的，那我们明天见。',
      '非常感谢您的详细介绍。'
    ]

    const randomReply = replies[Math.floor(Math.random() * replies.length)]

    const replyMessage = {
      id: messages.value.length + 1,
      sender: 'them',
      text: randomReply,
      time: new Date().toLocaleTimeString('zh-CN', { hour: '2-digit', minute: '2-digit' })
    }

    messages.value.push(replyMessage)

    // 滚动到底部
    scrollToBottom()
  }, 2000)
}

// 滚动到底部
const scrollToBottom = () => {
  nextTick(() => {
    if (messagesContainer.value) {
      messagesContainer.value.scrollTop = messagesContainer.value.scrollHeight
    }
  })
}

// 初始化WebSocket连接（模拟）
const initWebSocket = () => {
  // 模拟WebSocket连接
  console.log('连接到WebSocket服务器...')

  // 模拟连接成功
  setTimeout(() => {
    console.log('WebSocket连接成功')
  }, 1000)
}

// 关闭WebSocket连接
const closeWebSocket = () => {
  if (websocket) {
    websocket.close()
    console.log('WebSocket连接已关闭')
  }
}

// 页面加载时初始化
onMounted(() => {
  // 初始化WebSocket连接
  initWebSocket()

  // 滚动到底部
  scrollToBottom()
})

// 页面卸载前关闭WebSocket连接
onBeforeUnmount(() => {
  closeWebSocket()
})
</script>

<style scoped>
.chat-container {
  display: flex;
  min-height: 100vh;
  overflow: hidden;
  position: relative;
  background: linear-gradient(135deg, #6a11cb 0%, #2575fc 100%);
}

.background-decoration {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  overflow: hidden;
  z-index: 0;
}

/* 精美的动态背景 */
.dynamic-background {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background: linear-gradient(to bottom, #1a2980, #26d0ce);
  overflow: hidden;
}

/* 建筑物 */
.building {
  position: absolute;
  bottom: 0;
  background: rgba(30, 30, 50, 0.8);
  border-radius: 5px 5px 0 0;
  box-shadow: 0 -5px 15px rgba(0, 0, 0, 0.3);
}

.building-1 {
  left: 10%;
  width: 80px;
  height: 300px;
  animation: buildingGlow 4s infinite alternate;
}

.building-2 {
  left: 25%;
  width: 120px;
  height: 400px;
  animation: buildingGlow 5s infinite alternate-reverse;
}

.building-3 {
  left: 45%;
  width: 100px;
  height: 350px;
  animation: buildingGlow 6s infinite alternate;
}

.building-4 {
  left: 65%;
  width: 140px;
  height: 450px;
  animation: buildingGlow 4.5s infinite alternate-reverse;
}

.building-5 {
  left: 80%;
  width: 90px;
  height: 320px;
  animation: buildingGlow 5.5s infinite alternate;
}

@keyframes buildingGlow {
  0% {
    box-shadow: 0 -5px 15px rgba(0, 0, 0, 0.3);
  }
  100% {
    box-shadow: 0 -5px 25px rgba(100, 200, 255, 0.6);
  }
}

/* 云朵 */
.cloud {
  position: absolute;
  background: rgba(255, 255, 255, 0.8);
  border-radius: 50%;
  filter: blur(2px);
}

.cloud-1 {
  top: 20%;
  left: 5%;
  width: 80px;
  height: 30px;
  animation: cloudMove 25s linear infinite;
}

.cloud-2 {
  top: 35%;
  left: 70%;
  width: 120px;
  height: 40px;
  animation: cloudMove 30s linear infinite;
}

.cloud-3 {
  top: 15%;
  left: 40%;
  width: 100px;
  height: 35px;
  animation: cloudMove 35s linear infinite;
}

@keyframes cloudMove {
  0% {
    transform: translateX(-100px);
  }
  100% {
    transform: translateX(calc(100vw + 100px));
  }
}

/* 太阳 */
.sun {
  position: absolute;
  top: 80px;
  right: 100px;
  width: 80px;
  height: 80px;
  background: radial-gradient(circle, #ffeb3b, #ffc107);
  border-radius: 50%;
  box-shadow: 0 0 40px #ff9800, 0 0 80px #ff5722;
  animation: sunPulse 3s infinite alternate;
}

@keyframes sunPulse {
  0% {
    transform: scale(1);
    box-shadow: 0 0 40px #ff9800, 0 0 80px #ff5722;
  }
  100% {
    transform: scale(1.1);
    box-shadow: 0 0 60px #ff9800, 0 0 100px #ff5722;
  }
}

/* 光线 */
.light-ray {
  position: absolute;
  top: 120px;
  right: 140px;
  width: 400px;
  height: 200px;
  background: linear-gradient(to right, transparent, rgba(255, 235, 59, 0.2), transparent);
  transform-origin: left center;
  animation: rayRotate 10s infinite linear;
}

.ray-1 {
  transform: rotate(0deg);
  animation-delay: 0s;
}

.ray-2 {
  transform: rotate(60deg);
  animation-delay: 2s;
}

.ray-3 {
  transform: rotate(120deg);
  animation-delay: 4s;
}

@keyframes rayRotate {
  0% {
    transform: rotate(0deg);
  }
  100% {
    transform: rotate(360deg);
  }
}

/* 浮动装饰元素 */
.floating-shape {
  position: absolute;
  border-radius: 50%;
  background: rgba(255, 255, 255, 0.1);
  animation: float 15s infinite linear;
}

.shape-1 {
  width: 300px;
  height: 300px;
  top: -100px;
  left: -100px;
  animation-duration: 20s;
  background: radial-gradient(circle, rgba(74, 144, 226, 0.2) 0%, transparent 70%);
}

.shape-2 {
  width: 200px;
  height: 200px;
  bottom: -80px;
  right: -80px;
  animation-duration: 25s;
  animation-direction: reverse;
  background: radial-gradient(circle, rgba(255, 107, 107, 0.2) 0%, transparent 70%);
}

.shape-3 {
  width: 150px;
  height: 150px;
  top: 30%;
  right: 20%;
  animation-duration: 15s;
  background: radial-gradient(circle, rgba(80, 227, 194, 0.2) 0%, transparent 70%);
}

.shape-4 {
  width: 100px;
  height: 100px;
  bottom: 20%;
  left: 20%;
  animation-duration: 18s;
  animation-direction: reverse;
  background: radial-gradient(circle, rgba(255, 209, 102, 0.2) 0%, transparent 70%);
}

.shape-5 {
  width: 250px;
  height: 250px;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  animation-duration: 22s;
  background: radial-gradient(circle, rgba(155, 89, 182, 0.2) 0%, transparent 70%);
}

.shape-6 {
  width: 180px;
  height: 180px;
  top: 70%;
  left: 10%;
  animation-duration: 28s;
  background: radial-gradient(circle, rgba(231, 76, 60, 0.2) 0%, transparent 70%);
}

@keyframes float {
  0% {
    transform: translate(0, 0) rotate(0deg);
  }
  25% {
    transform: translate(20px, 20px) rotate(90deg);
  }
  50% {
    transform: translate(0, 40px) rotate(180deg);
  }
  75% {
    transform: translate(-20px, 20px) rotate(270deg);
  }
  100% {
    transform: translate(0, 0) rotate(360deg);
  }
}

.chat-wrapper {
  flex: 1;
  display: flex;
  flex-direction: column;
  z-index: 1;
  position: relative;
}

.top-navbar {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 15px 30px;
  background: rgba(0, 0, 0, 0.2);
  backdrop-filter: blur(10px);
  box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
}

.app-title {
  color: white;
  font-size: 24px;
  font-weight: 700;
  margin: 0;
}

.navbar-center {
  flex: 1;
  margin: 0 20px;
}

:deep(.el-menu--horizontal) {
  border: none;
  background: transparent !important;
}

:deep(.el-menu--horizontal .el-menu-item) {
  color: white;
  border: none;
}

:deep(.el-menu--horizontal .el-menu-item:hover) {
  background: rgba(255, 255, 255, 0.2) !important;
}

:deep(.el-menu--horizontal .el-menu-item.is-active) {
  color: #4A90E2 !important;
  border: none;
}

.user-info {
  display: flex;
  align-items: center;
  gap: 10px;
  cursor: pointer;
  color: white;
}

.username {
  font-size: 16px;
  font-weight: 500;
}

.main-content {
  display: flex;
  flex: 1;
  overflow: hidden;
}

.sidebar {
  width: 250px;
  background: rgba(0, 0, 0, 0.3);
  backdrop-filter: blur(10px);
  padding: 20px 0;
  height: 100%;
  box-shadow: 3px 0 10px rgba(0, 0, 0, 0.2);
}

.el-menu-vertical {
  border: none !important;
  height: 100%;
}

.el-menu-item,
.el-sub-menu__title {
  margin: 5px 10px;
  border-radius: 8px;
  transition: all 0.3s ease;
}

.el-menu-item:hover,
.el-sub-menu__title:hover {
  background-color: rgba(255, 255, 255, 0.1) !important;
}

.content-area {
  flex: 1;
  display: flex;
  flex-direction: column;
  background: rgba(255, 255, 255, 0.85);
  backdrop-filter: blur(10px);
  overflow: hidden;
}

.chat-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 15px 20px;
  background: white;
  border-bottom: 1px solid #eee;
  box-shadow: 0 2px 10px rgba(0, 0, 0, 0.05);
}

.header-left {
  display: flex;
  align-items: center;
  gap: 15px;
}

.user-info {
  display: flex;
  align-items: center;
  gap: 15px;
}

.user-details h3 {
  margin: 0;
  font-size: 18px;
  color: #2c3e50;
}

.user-details p {
  margin: 5px 0 0;
  font-size: 14px;
  color: #7f8c8d;
}

.user-details .status.online {
  color: #50E3C2;
}

.chat-messages {
  flex: 1;
  overflow-y: auto;
  padding: 20px;
  background: #f5f7fa;
}

.messages-list {
  display: flex;
  flex-direction: column;
  gap: 20px;
}

.message-item {
  display: flex;
  max-width: 80%;
}

.message-item.sent {
  align-self: flex-end;
  flex-direction: row-reverse;
}

.message-item.received {
  align-self: flex-start;
}

.message-content {
  display: flex;
  flex-direction: column;
  gap: 5px;
}

.message-item.sent .message-content {
  align-items: flex-end;
}

.message-item.received .message-content {
  align-items: flex-start;
}

.message-text {
  padding: 12px 16px;
  border-radius: 18px;
  font-size: 14px;
  line-height: 1.5;
  word-wrap: break-word;
  max-width: 100%;
}

.message-item.sent .message-text {
  background: #4A90E2;
  color: white;
  border-bottom-right-radius: 4px;
}

.message-item.received .message-text {
  background: white;
  color: #2c3e50;
  border-bottom-left-radius: 4px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.08);
}

.message-time {
  font-size: 12px;
  color: #7f8c8d;
}

.chat-input {
  display: flex;
  flex-direction: column;
  gap: 10px;
  padding: 15px 20px;
  background: white;
  border-top: 1px solid #eee;
}

.input-tools {
  display: flex;
  gap: 10px;
}

.input-actions {
  display: flex;
  justify-content: flex-end;
}

@media (max-width: 992px) {
  .sidebar {
    width: 80px;
  }

  .app-title,
  .el-menu-item span,
  .el-sub-menu__title span {
    display: none;
  }

  .chat-header {
    flex-direction: column;
    gap: 15px;
    align-items: flex-start;
  }

  .header-left,
  .header-right {
    width: 100%;
  }

  .message-item {
    max-width: 90%;
  }
}
</style>
